import ch.sfug.events.ErrorEvent;
import ch.sfug.events.Event;
import ch.sfug.events.HTTPStatusEvent;
import ch.sfug.net.loader.AbstractLoader;

/**
 * @author mih
 */

class ch.sfug.net.loader.VarsLoader extends AbstractLoader {

	private var result_lv:LoadVars;

	/**
	 * constructor
	 * @param theUrl the loadvars url
	 * @param noCache (optional) if true the loaded url will contain a random number to prevent caching. default is false.
	 */
	public function VarsLoader( theUrl:String, noCache:Boolean ) {
		super( theUrl, noCache );
	}


	/**
	 * starts to load (GET) vars from the given url
	 * @param theUrl (optional) reassign url before loading
	 * @param noCache (optional) if true the loaded url will contain a random number to prevent caching. default is false.
	 */
	public function load( theUrl:String, noCache:Boolean ):Void {
		url = theUrl;
		preventCacheing = noCache;
		init();
		result_lv.load( url );
	}

	/**
	 * sends a loadvars object to the url and gets the result
	 * @param lv a loadvars object to send to the url and get the result back
	 * @param method (optional) the method how to send the vars. default is POST.
	 * @param theUrl (optional) reassign url before loading
	 * @param noCache (optional) if true the loaded url will contain a random number to prevent caching. default is false.
	 */
	public function sendVar( lv:LoadVars, method:String, theUrl:String, noCache:Boolean ):Void {
		url = theUrl;
		preventCacheing = noCache;
		init();
		method = ( method == undefined ) ? "POST" : method;
		lv.sendAndLoad( url, result_lv, method );
		dispatchEvent( new Event( Event.OPEN ) );
	}

	/**
	 * returns the result loadvars object
	 */
	public function getResult():LoadVars {
		return result_lv;
	}

	/**
	 * resets the loadvars object
	 */
	private function init(  ):Void {
		result_lv = new LoadVars();
		var t:VarsLoader = this;

		result_lv.onLoad = function(suc:Boolean):Void {
			t.onLoad(suc);
		};
		result_lv.onHTTPStatus = function(num:Number):Void {
			t.onHTTPStatus(num);
		};
	}

	/**
	 * catch the event from the result_lv file to dispatch the complete event
	 */
	private function onLoad(success:Boolean):Void {
		if(success) {
			dispatchEvent( new Event( Event.COMPLETE ) );
		} else {
			dispatchEvent( new ErrorEvent( ErrorEvent.ERROR, getErrorDesc( -1 ) ) );
		}
	}

	/**
	 * catch the event from the result_lv file to dispatch the httpstatus event
	 */
	private function onHTTPStatus(status:Number):Void {
		dispatchEvent( new HTTPStatusEvent( HTTPStatusEvent.HTTPSTATUS, status ) );
	}

	/**
	 * returns the error description of the result_lv error
	 */
	private function getErrorDesc(num:Number):String {
		switch (num) {
			case -1:
				return "Could not load the file from url: " + url;
		}
	}

}